import json
import time
from urllib.request import urlopen

def unixtime() -> int:
    return int(time.time())

def unixday() -> int:
    t = unixtime()
    t += 28800 # 加8小时，调为北京时间
    t -= t % 86400 # 去零头，取0时
    t -= 28800 # 减8小时，调为伦敦时间
    return t

# 视频API
def call_api_web(aid: int):
    url = 'http://api.bilibili.com/x/web-interface/view?aid={0}'.format(aid)
    txt = urlopen(url).read().decode('utf-8', 'ignore')
    return json.loads(txt)

# 频道API
def call_api_channel(channel: int, offset: int = 0):
    url = 'https://api.bilibili.com/x/web-interface/web/channel/multiple/list?channel_id={0}&sort_type=new&page_size=30'.format(channel)
    if offset != 0:
        url += "&offset={0}".format(offset)
    txt = urlopen(url).read().decode('utf-8', 'ignore')
    return json.loads(txt)

# 递归调用频道API，直到曲目的投稿时间早于start_time为止
def get_recent_videos(channel: int, start_time: int, recorder: dict, cache: dict):
    earlist_pubdate = unixtime()
    offset = 0
    cnt = 0
    while earlist_pubdate >= start_time:
        json_data = call_api_channel(channel, offset)
        data = json_data['data']
        list = data['list']
        offset = data['offset']
        # 对于列表中的数据，逐一调用视频API，查询各项数据
        for v in list:
            aid = v['id']
            # 如果缓存中有，就从缓存中提取
            if cache and aid in cache:
                recorder[aid] = cache[aid]
                continue
            video = dict()
            # 搬运5个属性到video里
            video['aid'] = v['id']
            video['title'] = v['name']
            for key in ['bvid', 'author_id', 'author_name']:
                video[key] = v[key]
            # 调用视频具体数据的API
            video_data = call_api_web(aid) ['data']
            video['pubdate'] = video_data['pubdate']
            if video['pubdate'] < start_time:
                earlist_pubdate = video['pubdate']
                break
            video['copyright'] = video_data['copyright']
            stat = video_data['stat']
            keys = ['view', 'danmaku', 'reply', 'favorite', 'coin', 'share', 'like']
            for key in keys:
                video[key] = stat[key]
            video['added'] = unixtime()
            cnt += 1
            print(cnt, '\t', video['title'])
            recorder[aid] = video
    return recorder   

# 写入文件
def write_file(json_data, file_path):
    with open(file_path, 'w', encoding='utf8') as file_obj:
        json.dump(json_data, file_obj, ensure_ascii=False)

# main
lty_videos = dict() #8564
yh_videos = dict() #129641
day = unixday() #日期
length = 86400 * 14 #两周

print("\n\n 开始获取洛天依数据")
get_recent_videos(8564, unixtime() - length, lty_videos, None)
write_file(list(lty_videos.values()), ".\lty_{0}.json".format(day))

print("\n\n 开始获取言和数据")
get_recent_videos(129641, unixtime() - length, yh_videos, lty_videos)
write_file(list(yh_videos.values()), ".\yh_{0}.json".format(day))

print("\n\n 运行完毕")
